import { ref } from 'vue';
import app from '@/app'
import store from '@/app/store'
import { template as getStore } from '@/api/manage'
import { template, templateSave, templateDelete } from '@/api/erp/config'
import accountStore from '@/store/account'

// 初始化
const templateStore = store()

templateStore.get = () => {
  return new Promise((resolve, jeject) => {
    template().then(res => {
      templateStore.setList(res)
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 设置模版
templateStore.update = (data) => {
  return new Promise((resolve, jeject) => {
    templateSave(data).then(res => {
      templateStore.get()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 删除模版
templateStore.delete = (data) => {
  return new Promise((resolve, jeject) => {
    templateDelete(data).then(res => {
      templateStore.get()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 打开store
templateStore.store = ref({})
templateStore.getStore = () => {
  return new Promise((resolve, jeject) => {
    getStore().then(res => {
      // 按关键字归类
      const store = {}
      res.forEach(item => {
        const keyword = item.keyword
        if(!store[keyword]) {
          store[keyword] = []
        }
        store[keyword].push(item)
      })
      templateStore.store.value = store
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 判断模版选中
templateStore.has = data => {
  // 获取模版
  const template = templateStore.id(data.id)

  return !!template
}

// 判断模版更新
templateStore.hasUpdate = data => {
  // 获取模版
  const template = templateStore.id(data.id)

  if(!template) return template

  // 判断是否同一ID并且内容不一样
  return template.html != data.html
}

// ID获取模版
templateStore.id = (id) => {
  return templateStore.getList().find(item => item.id == id)
}

// 获取模版信息
templateStore.keyword = (keyword) => {
  return templateStore.getList().filter(item => item.keyword == 'erp_' + keyword)
}

// 使用模版
templateStore.make = (name, index = 0) => {
  const template = templateStore.keyword(name)
  if(!template.length) return

  // 循环解析模版数据
  const data = {}
  template[index].data.forEach(item => {
    data[item.key] = item.value
  })

  return { view: template[index].html, data }
}

// 编译模版
templateStore.build = async(view, data, template) => {
  const user = accountStore.getData().user
  const account = accountStore.getData()
  const logo = await app.imgurl(app.img(user.logo))
  return eval('(() => {' + view + '})()', data, template, user, account, logo)
}

export default templateStore